package org.ofbiz.wvtools.word;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilValidate;

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;

import javolution.util.FastMap;

public class WordUtils {

    public static String module = WordUtils.class.getName();
    public static String OFBIZ_HOME = System.getProperty("ofbiz.home") + "/hot-deploy/sys/webapp/sys";

    public static void main(String args[]) throws IOException {
	String wordTemplatePath = "C:\\Users\\Shinelon\\Desktop\\";
	String newFileName = "333.docx";
	
	String oldFileName = "2222.docx";
	String newFileName2 = "2222.pdf";
	Document doc = new Document();
	doc.loadFromFile(wordTemplatePath+newFileName);
	
	doc.replace("合同", "合同",false,true);
//	doc.replace("${日期}", "2020-11-30",false,true);
//	doc.replace("${甲方签名}", "上海欧弗",false,true);
//	doc.replace("${乙方签名}", "杨朋",false,true);
	// 保存为Docx格式
	doc.saveToFile(wordTemplatePath + oldFileName, FileFormat.Docx);
	//保存为pdf格式
	doc.saveToFile(wordTemplatePath + newFileName2, FileFormat.PDF);
	System.out.println(11111);

    }

    @SuppressWarnings("rawtypes")
    public static Map<String, String> createDocx(String path, Map replaceMap,String filePath) {
	Map<String, String> result = FastMap.newInstance();
	try {
	    result = FastMap.newInstance();
	    String name = path.substring(path.lastIndexOf("/") + 1, path.length());
	    if(UtilValidate.isEmpty(filePath)) {
		filePath = path.substring(0, path.lastIndexOf("/")).replace("sysServer", "") + "/";
	    }
	    path = OFBIZ_HOME + path.replace("sysServer", "");
	    Document doc = new Document();
	    doc.loadFromFile(path);
	    if (UtilValidate.isNotEmpty(replaceMap)) {
	        Iterator keys = replaceMap.keySet().iterator();
	        while (keys.hasNext()) {
	    	   String key = (String) keys.next();
	    	   String value = (String) replaceMap.get(key);
	    	   doc.replace("${" + key + "}", value, false, true);
	        }
	    }

	    String docPath = "";
	    String newName = name.substring(0, name.lastIndexOf("."));
	    String newPath = filePath + "doc/";
	    File parentDir = new File(OFBIZ_HOME + newPath);
	    if (!parentDir.exists()) {
	        parentDir.mkdirs();
	    }

	    System.out.println(newName);
	    if (name.contains("docx")) {
	        name = name.substring(0, name.lastIndexOf("."));
	        // 保存为Docx格式
	        doc.saveToFile(OFBIZ_HOME + newPath + newName + ".docx", FileFormat.Docx);
	        docPath = "sysServer" + newPath + name + ".docx";
	    } else {
	        name = name.substring(0, name.lastIndexOf("."));
	        doc.saveToFile(OFBIZ_HOME + newPath + newName + ".doc", FileFormat.Doc);
	        docPath = "sysServer" + newPath + name + ".doc";
	    }
	    // 保存pdf文件
//	    doc.saveToFile(OFBIZ_HOME + newPath + newName + ".pdf", FileFormat.PDF);
//	    String pdfPath = "sysServer" + newPath + name + ".pdf";
	    result.put("docPath", docPath);
	} catch (Exception e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }
    
    
    
    @SuppressWarnings("rawtypes")
    public static Map<String, String> createDocx(String path, Map replaceMap,Map replaceImgMap,String filePath) {
	Map<String, String> result = FastMap.newInstance();
	try {
	    result = FastMap.newInstance();
	    String name = path.substring(path.lastIndexOf("/") + 1, path.length());
	    if(UtilValidate.isEmpty(filePath)) {
		filePath = path.substring(0, path.lastIndexOf("/")).replace("sysServer", "") + "/";
	    }
	    path = OFBIZ_HOME + path.replace("sysServer", "");
	    Document doc = new Document();
	    doc.loadFromFile(path);
	    if (UtilValidate.isNotEmpty(replaceMap)) {
	        Iterator keys = replaceMap.keySet().iterator();
	        while (keys.hasNext()) {
	    	   String key = (String) keys.next();
	    	   String value = (String) replaceMap.get(key);
	    	   doc.replace("${" + key + "}", value, false, true);
	        }
	    }
	    if(UtilValidate.isNotEmpty(replaceImgMap)) {
		Iterator keys = replaceImgMap.keySet().iterator();
	        while (keys.hasNext()) {
	    	   String key = (String) keys.next();
	    	   String value = (String) replaceImgMap.get(key);
	    	   TextSelection[] selections = doc.findAllString("${" + key + "}", true, true);
	    	//用图片替换文字
	           int index = 0;
	           TextRange range = null;
	           for (Object obj : selections) {
	               TextSelection textSelection = (TextSelection)obj;
	               DocPicture pic = new DocPicture(doc);
	               String picImg = OFBIZ_HOME + value.replace("sysServer", "");
	               pic.loadImage(picImg);
	               range = textSelection.getAsOneRange();
	               index = range.getOwnerParagraph().getChildObjects().indexOf(range);
	               range.getOwnerParagraph().getChildObjects().insert(index,pic);
	               range.getOwnerParagraph().getChildObjects().remove(range);
	           }
	        }
	    }
	    String docPath = "";
	    String newName = name.substring(0, name.lastIndexOf("."));
	    String newPath = filePath + "doc/";
	    File parentDir = new File(OFBIZ_HOME + newPath);
	    if (!parentDir.exists()) {
	        parentDir.mkdirs();
	    }

	    System.out.println(newName);
	    if (name.contains(".docx")) {
	        name = name.substring(0, name.lastIndexOf("."));
	        // 保存为Docx格式
	        doc.saveToFile(OFBIZ_HOME + newPath + newName + ".docx", FileFormat.Docx);
	        docPath = "sysServer" + newPath + name + ".docx";
	    } else {
	        name = name.substring(0, name.lastIndexOf("."));
	        doc.saveToFile(OFBIZ_HOME + newPath + newName + ".doc", FileFormat.Doc);
	        docPath = "sysServer" + newPath + name + ".doc";
	    }
	    // 保存pdf文件
//	    doc.saveToFile(OFBIZ_HOME + newPath + newName + ".pdf", FileFormat.PDF);
//	    String pdfPath = "sysServer" + newPath + name + ".pdf";
	    result.put("docPath", docPath);
	} catch (Exception e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }
    
}
